package com.cheer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheer.dao.AccountDao;
import com.cheer.dto.AccountBackupUpdateDTO;
import com.cheer.dto.AccountUpdateDTO;
import com.cheer.dto.PasswordUpdateDTO;
import com.cheer.entity.Account;
import com.cheer.exception.ServiceException;
import com.cheer.manager.AccountManager;
import com.cheer.service.AccountService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class AccountServiceImpl extends ServiceImpl<AccountDao, Account> implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private AccountManager accountManager;

    @Override
    public void updatePassword(Long accountId, PasswordUpdateDTO passwordUpdateDTO) {
        // 校验参数
        if (!StringUtils.equals(passwordUpdateDTO.getPassword(), passwordUpdateDTO.getConfirmPassword())) {
            throw new ServiceException("两次密码输入不一致");
        }
        Account account = accountDao.selectById(accountId);
        if (account == null || account.getLocked()) {
            throw new ServiceException("账号已失效");
        }
        if (!StringUtils.equals(passwordUpdateDTO.getAnswer(), account.getSecurityAnswer())) {
            throw new ServiceException("答案填写不正确");
        }
        // 修改密码
        accountManager.updatePassword(accountId, passwordUpdateDTO.getPassword());
    }

    @Override
    @Transactional
    public void updatePhone(Long accountId, AccountUpdateDTO accountUpdateDTO) {
        // 检查密码
        Account account = accountManager.checkPassword(accountId, accountUpdateDTO.getPassword());
        // 修改账号
        accountManager.updatePhone(accountUpdateDTO.getPhone(), account);
    }

    @Override
    @Transactional
    public void updateBackup(Long accountId, AccountBackupUpdateDTO accountBackupUpdateDTO) {
        // 检查密码
        Account account = accountManager.checkPassword(accountId, accountBackupUpdateDTO.getPassword());
        // 修改备用账号
        accountManager.updateBackAccount(accountBackupUpdateDTO.getBackupAccount(), account);
    }

    @Override
    public String getSecurityQuestion(Long accountId) {
        Account account = accountDao.selectById(accountId);
        if (account == null || account.getLocked()) {
            throw new ServiceException("账号已失效");
        }
        return account.getSecurityQuestion();
    }

    @Override
    public List<Account> listByRoleIds(ArrayList<Integer> accounts) {

        List<Account> accountRecords =  accountDao.listByRoleIds(accounts);

        return accountRecords;
    }
}

